#include "MainWindow.h"

#include <QApplication>
#include <QTextCodec>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QMutex>

#include <stdio.h>

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug");
        break;

    case QtWarningMsg:
        text = QString("Warning");
        break;

    case QtCriticalMsg:
        text = QString("Critical");
        break;

    case QtFatalMsg:
        text = QString("Fatal");
        break;
    case QtInfoMsg:
        text = QString("Info");
    }

    QString currentDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ");
    QString message = QString("(%1) %2:%3 (%4) %5\n")
            .arg(currentDateTime)
            .arg(context.file).arg(context.line)
            .arg(text).arg(msg);

    // stderr
    fprintf(stderr, "%s", message.toLocal8Bit().constData());
    fflush(stderr);

    // log file
    QString fileName = qApp->applicationDirPath() + "/launcher.log";

    QFile file(fileName);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message;
    file.flush();
    file.close();

    mutex.unlock();
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(outputMessage);
    QApplication a(argc, argv);
    a.setApplicationName("WebdavClient");
    a.setDesktopFileName(PkgName);
    a.setApplicationVersion(PkgVersion);
    a.setWindowIcon(QIcon(":/Icons/WebdavClient.svg"));

    // 单例服务
    const QString serverName = PkgName;
    QLocalSocket socket;
    socket.connectToServer(serverName);

    // 检查是否已有实例运行
    if (socket.waitForConnected(500)) {
        qCritical() << Q_FUNC_INFO << "程序已在运行中！";

        // 可选：发送消息激活已有实例
        socket.write("ACTIVATE");
        socket.flush();
        socket.close();

        return 0;
    }
    // 创建本地服务器
    QLocalServer server;
    server.removeServer(serverName);
    if (!server.listen(serverName)) {
        QMessageBox::critical(nullptr, "错误", "无法创建单例锁！");
        return 1;
    }

    MainWindow w;
    QObject::connect(&server, &QLocalServer::newConnection, [&]() {
        QLocalSocket *client = server.nextPendingConnection();
        // 收到激活请求时唤醒窗口
        w.hide();
        w.showNormal();
        w.activateWindow();
        client->deleteLater();
    });
    w.resize(1200, 720);
    w.show();
    return a.exec();
}
